<?php
/**
 * Database wrapper class
 * 
 * @author Wouter Bakker
 */
class Database {
	
	private static $instance = null;
	private $database;
	
	private function __construct(){
		$config = Config::getInstance();
		try{
			$this->database = new PDO('mysql:host='.$config->dbCredentials['hostname']
									.';dbname='.$config->dbCredentials['db_name'],
									$config->dbCredentials['username'],
									$config->dbCredentials['password']
								);
			$this->database->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
			$this->database->query('SET NAMES utf8');
			$this->database->num_queries = 0;
		}
		catch(PDOException $e){
			echo "<pre>".$e->__toString()."</pre>";
		}
	}
	
	private function __clone(){
		//enforece singleton
	}
	
	public static function getInstance(){
		return is_object(self::$instance) ? self::$instance : (self::$instance = new self() );
	}
	
	public function dbQuery($query){
		try{
			$q = $this->database->query($query);
			$this->database->num_queries++;
			return $q;
		}
		catch(PDOException $e){
			echo "<pre>".$e->__toString()."</pre>";
		}
	}

	public function dbRow($query){
		try{
			$q = $this->dbQuery($query);
			return $q->fetch(PDO::FETCH_ASSOC);
		}
		catch(PDOException $e){
			echo "<pre>".$e->__toString()."</pre>";
		}
	}

	public function dbOne($query, $field=''){
		$r = $this->dbRow($query);
		return $r[$field];
	}

	public function dbAll($query, $key=''){
		try{
			$q = $this->dbQuery($query);
			$results = array();
			while($r = $q->fetch(PDO::FETCH_ASSOC)) $results[] = $r;
			if(!$key) return $results;
			$arr = array();
			foreach($results as $r) $arr[$r[$key]] = $r;
			return $arr;
		}
		catch(PDOException $e){
			echo "<pre>".$e->__toString()."</pre>";
		}
	}

	public function dbLastInsertId(){
		return $this->dbOne('SELECT last_insert_id() as id', 'id');
	}
	
	
}
